<?php

/**
 * This file is part of ossecdb-extjs.
 * 
 * Copyright (C) 2011 Brendan Johnston
 * 
 * Contact: brendan@johnston.net.au
 * 
 * Project: http://code.google.com/p/ossecdb-extjs/
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

class ossec_db
{
	static $db;

	static function db ()
	{
		global $config;

		if (self::$db == null)
		{
			self::$db = new PDO(
				$config['pdo_dsn'],
				$config['pdo_username'],
				$config['pdo_password'],
				$config['pdo_driver_options']
			);
		}

		return self::$db;
	}

	static function close ()
	{
		self::$db = null;
	}

	static function query ($sql, $unset_null = false)
	{
		$statement = self::db()->prepare($sql);
		$statement->execute();
		$result = $statement->fetchAll(PDO::FETCH_OBJ);
		if ($unset_null)
		{
			foreach ($result as $row)
			{
				foreach ($row as $name => $value)
				{
					if (!isset($value))
					{
						unset($row->{$name});
					}
				}
			}
		}
		return $result;
	}

	static function result ($tsql, $dsql, $unset_null = false)
	{
		if ($total = self::query($tsql))
		{
			$result = (object) array(
				'total' => $total[0]->total, 'data' => self::query($dsql, $unset_null)
			);

			return $result;
		}
	}
}

// For use in array_map
function ossec_db_quote ($v)
{
	return ossec_db::db()->quote($v);
}

class ossec_views
{
	static function cols_to_select ($cols) 
	{
		$select = array();

		foreach ($cols as $as => $col)
		{
			$select[] = "$col as `$as`";
		}

		return implode(', ', $select);
	}
}

?>